/**
 * permission-utils.js
 * 权限检查工具模块
 * 
 * 功能：
 * - 提供收入记录权限检查函数
 * - 提供病例记录权限检查函数
 * - 支持角色基础权限检查
 * - 支持临时授权检查
 */

const db = uniCloud.database();
const _ = db.command;

/**
 * 角色权限映射表
 * 定义各角色对收入记录的基础权限
 */
const INCOME_RECORD_PERMISSIONS = {
	// 查看权限
	view: {
		// 可查看所有记录的角色
		all: ['admin', 'director', 'finance'],
		// 可查看除院长外所有记录的角色
		exclude_director: ['vice_director'],
		// 仅可查看自己记录的角色
		self: ['head_nurse', 'administrative', 'purchaser']
	},
	// 编辑权限
	edit: {
		// 可编辑所有记录的角色
		all: ['admin', 'finance'],
		// 可编辑自己记录的角色
		self: []
	},
	// 删除权限
	delete: {
		// 可删除所有记录的角色
		all: ['admin', 'finance'],
		// 可删除自己记录的角色
		self: []
	},
	// 增加权限
	add: {
		// 可增加记录的角色
		all: ['admin', 'finance'],
		// 可增加自己记录的角色
		self: []
	}
};

/**
 * 角色权限映射表
 * 定义各角色对病例记录的基础权限
 */
const MEDICAL_RECORD_PERMISSIONS = {
	// 查看权限
	view: {
		// 可查看所有记录的角色
		all: ['admin', 'director'],
		// 可查看除院长外所有记录的角色
		exclude_director: ['vice_director'],
		// 可查看自己主治的病例
		self_doctor: ['doctor'],
		// 可查看自己协助的病例
		self_assistant: ['nurse', 'head_nurse']
	},
	// 编辑权限
	edit: {
		// 可编辑所有记录的角色
		all: ['admin', 'director'],
		// 可编辑自己主治的病例
		self_doctor: ['doctor'],
		// 可编辑自己协助的病例
		self_assistant: ['nurse', 'head_nurse']
	},
	// 删除权限
	delete: {
		// 可删除所有记录的角色
		all: ['admin', 'director'],
		// 可删除自己主治的病例
		self_doctor: ['doctor'],
		// 可删除自己协助的病例
		self_assistant: ['nurse', 'head_nurse']
	}
};


// 权限缓存对象
const permissionCache = {
	userRoles: new Map(),
	temporaryAuth: new Map(),
	cacheTimeout: 5 * 60 * 1000, // 5分钟缓存超时
};

/**
 * 清理过期的权限缓存
 */
function clearExpiredCache() {
	const now = Date.now();
	
	// 清理用户角色缓存
	for (const [key, value] of permissionCache.userRoles.entries()) {
		if (now - value.timestamp > permissionCache.cacheTimeout) {
			permissionCache.userRoles.delete(key);
		}
	}
	
	// 清理临时授权缓存
	for (const [key, value] of permissionCache.temporaryAuth.entries()) {
		if (now - value.timestamp > permissionCache.cacheTimeout) {
			permissionCache.temporaryAuth.delete(key);
		}
	}
}

/**
 * 通用权限检查函数
 * @param {String} userId - 用户ID
 * @param {String} resourceType - 资源类型，如 'income_record', 'medical_record'
 * @param {String} action - 操作类型：'view', 'edit', 'delete', 'add'
 * @param {String} recordUserId - 资源关联的用户ID（可选，用于检查是否为本人记录）
 * @returns {Promise<Object>} 权限检查结果 { hasPermission: boolean, reason: string }
 */
async function checkPermission(userId, resourceType, action, recordUserId = null) {
	try {
		// 清理过期缓存
		clearExpiredCache();
		
		// 获取权限配置
		const permissionConfig = getPermissionConfig(resourceType);
		if (!permissionConfig) {
			return {
				hasPermission: false,
				reason: `不支持的资源类型: ${resourceType}`
			};
		}
		
		// 获取操作权限配置
		const actionConfig = permissionConfig[action];
		if (!actionConfig) {
			return {
				hasPermission: false,
				reason: `不支持的操作类型: ${action}`
			};
		}
		
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 检查是否可对所有资源执行操作
		if (hasAnyRole(userRoles, actionConfig.all)) {
			return {
				hasPermission: true,
				reason: `具有对所有${resourceType}执行${action}操作的权限`
			};
		}
		
		// 检查是否可对自己的资源执行操作
		if (hasAnyRole(userRoles, actionConfig.self) && recordUserId && recordUserId === userId) {
			return {
				hasPermission: true,
				reason: `具有对自己${resourceType}执行${action}操作的权限`
			};
		}
		
		// 检查是否可对除特定角色外的所有资源执行操作（仅适用于病例记录）
		if (resourceType === 'medical_record' && action === 'view' && 
			hasAnyRole(userRoles, actionConfig.exclude_director)) {
			return {
				hasPermission: true,
				reason: `具有对除院长外所有${resourceType}执行${action}操作的权限`
			};
		}
		
		// 检查是否可对自己主治的病例执行操作（仅适用于病例记录）
		if (resourceType === 'medical_record' && 
			hasAnyRole(userRoles, actionConfig.self_doctor) && recordUserId && recordUserId === userId) {
			return {
				hasPermission: true,
				reason: `具有对自己主治的${resourceType}执行${action}操作的权限`
			};
		}
		
		// 检查是否可对自己协助的病例执行操作（仅适用于病例记录）
		if (resourceType === 'medical_record' && 
			hasAnyRole(userRoles, actionConfig.self_assistant) && recordUserId && recordUserId === userId) {
			return {
				hasPermission: true,
				reason: `具有对自己协助的${resourceType}执行${action}操作的权限`
			};
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, resourceType, action, recordUserId);
		if (tempAuthResult.hasPermission) {
			return tempAuthResult;
		}
		
		// 默认无权限
		return {
			hasPermission: false,
			reason: `无对${resourceType}执行${action}操作的权限`
		};
	} catch (error) {
		console.error('[checkPermission] 权限检查失败:', error);
		return {
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 获取资源类型的权限配置
 * @param {String} resourceType - 资源类型
 * @returns {Object|null} 权限配置
 */
function getPermissionConfig(resourceType) {
	switch (resourceType) {
		case 'income_record':
			return INCOME_RECORD_PERMISSIONS;
		case 'medical_record':
			return MEDICAL_RECORD_PERMISSIONS;
		default:
			return null;
	}
}

/**
 * 批量权限检查
 * @param {String} userId - 用户ID
 * @param {Array} permissionRequests - 权限请求数组，每个元素包含 { resourceType, action, recordUserId }
 * @returns {Promise<Array>} 权限检查结果数组
 */
async function batchCheckPermissions(userId, permissionRequests) {
	try {
		const results = [];
		
		for (const request of permissionRequests) {
			const { resourceType, action, recordUserId } = request;
			const result = await checkPermission(userId, resourceType, action, recordUserId);
			results.push({
				resourceType,
				action,
				recordUserId,
				...result
			});
		}
		
		return results;
	} catch (error) {
		console.error('[batchCheckPermissions] 批量权限检查失败:', error);
		return [];
	}
}

/**
 * 获取用户角色（带缓存）
 * @param {String} userId - 用户ID
 * @returns {Promise<Array>} 用户角色数组
 */
async function getUserRoles(userId) {
	try {
		// 检查缓存
		const cacheKey = `user:${userId}`;
		const cached = permissionCache.userRoles.get(cacheKey);
		
		if (cached && (Date.now() - cached.timestamp < permissionCache.cacheTimeout)) {
			return cached.roles;
		}
		
		if (!userId) {
			console.warn('[getUserRoles] 用户ID不能为空');
			return [];
		}
		
		const res = await db.collection('uni-id-users')
			.doc(userId)
			.field({ role: true })
			.get();
		
		const userData = res.result?.data || res.data;
		const user = Array.isArray(userData) ? (userData.length > 0 ? userData[0] : null) : userData;
		
		if (!user || !user.role) {
			return [];
		}
		
		const roles = Array.isArray(user.role) ? user.role : [user.role];
		
		// 更新缓存
		permissionCache.userRoles.set(cacheKey, {
			roles,
			timestamp: Date.now()
		});
		
		return roles;
	} catch (error) {
		console.error('[getUserRoles] 获取用户角色失败:', error);
		return [];
	}
}

/**
 * 检查用户是否具有指定角色
 * @param {Array} userRoles - 用户角色数组
 * @param {Array} requiredRoles - 需要的角色数组
 * @returns {Boolean} 是否具有任一指定角色
 */
function hasAnyRole(userRoles, requiredRoles) {
	if (!userRoles || !Array.isArray(userRoles) || userRoles.length === 0) {
		return false;
	}
	
	if (!requiredRoles || !Array.isArray(requiredRoles) || requiredRoles.length === 0) {
		return false;
	}
	
	return requiredRoles.some(role => userRoles.includes(role));
}

/**
 * 检查收入记录查看权限
 * @param {String} userId - 用户ID
 * @param {String} recordUserId - 收入记录关联的用户ID（可选，用于检查是否为本人记录）
 * @param {String} recordDirectorId - 收入记录关联的院长ID（可选，用于副院长排除院长记录）
 * @returns {Promise<Object>} 权限检查结果 { hasPermission: boolean, reason: string }
 */
async function checkIncomeRecordViewPermission(userId, recordUserId = null, recordDirectorId = null) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 检查是否可查看所有记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.view.all)) {
			return {
				hasPermission: true,
				reason: '具有查看所有收入记录的权限'
			};
		}
		
		// 检查是否可查看除院长外的所有记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.view.exclude_director)) {
			// 如果是院长记录，则无权查看
			if (recordDirectorId) {
				const directorRoles = await getUserRoles(recordDirectorId);
				if (hasAnyRole(directorRoles, ['director'])) {
					return {
						hasPermission: false,
						reason: '副院长无权查看院长的收入记录'
					};
				}
			}
			
			return {
				hasPermission: true,
				reason: '具有查看除院长外所有收入记录的权限'
			};
		}
		
		// 检查是否可查看自己的记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.view.self)) {
			if (recordUserId && recordUserId === userId) {
				return {
					hasPermission: true,
					reason: '具有查看自己收入记录的权限'
				};
			} else {
				return {
					hasPermission: false,
					reason: '只能查看自己的收入记录'
				};
			}
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, 'income_record', 'view', recordUserId);
		if (tempAuthResult.hasPermission) {
			return tempAuthResult;
		}
		
		// 默认无权限
		return {
			hasPermission: false,
			reason: '无查看收入记录的权限'
		};
	} catch (error) {
		console.error('[checkIncomeRecordViewPermission] 权限检查失败:', error);
		return {
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 检查收入记录编辑权限
 * @param {String} userId - 用户ID
 * @param {String} recordUserId - 收入记录关联的用户ID（可选，用于检查是否为本人记录）
 * @returns {Promise<Object>} 权限检查结果 { hasPermission: boolean, reason: string }
 */
async function checkIncomeRecordEditPermission(userId, recordUserId = null) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 检查是否可编辑所有记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.edit.all)) {
			return {
				hasPermission: true,
				reason: '具有编辑所有收入记录的权限'
			};
		}
		
		// 检查是否可编辑自己的记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.edit.self)) {
			if (recordUserId && recordUserId === userId) {
				return {
					hasPermission: true,
					reason: '具有编辑自己收入记录的权限'
				};
			} else {
				return {
					hasPermission: false,
					reason: '只能编辑自己的收入记录'
				};
			}
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, 'income_record', 'edit', recordUserId);
		if (tempAuthResult.hasPermission) {
			return tempAuthResult;
		}
		
		// 默认无权限
		return {
			hasPermission: false,
			reason: '无编辑收入记录的权限'
		};
	} catch (error) {
		console.error('[checkIncomeRecordEditPermission] 权限检查失败:', error);
		return {
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 检查收入记录删除权限
 * @param {String} userId - 用户ID
 * @param {String} recordUserId - 收入记录关联的用户ID（可选，用于检查是否为本人记录）
 * @returns {Promise<Object>} 权限检查结果 { hasPermission: boolean, reason: string }
 */
async function checkIncomeRecordDeletePermission(userId, recordUserId = null) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 检查是否可删除所有记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.delete.all)) {
			return {
				hasPermission: true,
				reason: '具有删除所有收入记录的权限'
			};
		}
		
		// 检查是否可删除自己的记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.delete.self)) {
			if (recordUserId && recordUserId === userId) {
				return {
					hasPermission: true,
					reason: '具有删除自己收入记录的权限'
				};
			} else {
				return {
					hasPermission: false,
					reason: '只能删除自己的收入记录'
				};
			}
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, 'income_record', 'delete', recordUserId);
		if (tempAuthResult.hasPermission) {
			return tempAuthResult;
		}
		
		// 默认无权限
		return {
			hasPermission: false,
			reason: '无删除收入记录的权限'
		};
	} catch (error) {
		console.error('[checkIncomeRecordDeletePermission] 权限检查失败:', error);
		return {
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 检查收入记录增加权限
 * @param {String} userId - 用户ID
 * @returns {Promise<Object>} 权限检查结果 { hasPermission: boolean, reason: string }
 */
async function checkIncomeRecordAddPermission(userId) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 检查是否可增加记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.add.all)) {
			return {
				hasPermission: true,
				reason: '具有增加收入记录的权限'
			};
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, 'income_record', 'add');
		if (tempAuthResult.hasPermission) {
			return tempAuthResult;
		}
		
		// 默认无权限
		return {
			hasPermission: false,
			reason: '无增加收入记录的权限'
		};
	} catch (error) {
		console.error('[checkIncomeRecordAddPermission] 权限检查失败:', error);
		return {
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 检查病例记录查看权限
 * @param {String} userId - 用户ID
 * @param {String} recordDoctorId - 病例记录的主治医生ID（可选）
 * @param {String} recordAssistantIds - 病例记录的协助人员ID数组（可选）
 * @param {String} recordDirectorId - 病例记录关联的院长ID（可选，用于副院长排除院长记录）
 * @returns {Promise<Object>} 权限检查结果 { hasPermission: boolean, reason: string }
 */
async function checkMedicalRecordViewPermission(userId, recordDoctorId = null, recordAssistantIds = null, recordDirectorId = null) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 检查是否可查看所有记录
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.view.all)) {
			return {
				hasPermission: true,
				reason: '具有查看所有病例记录的权限'
			};
		}
		
		// 检查是否可查看除院长外的所有记录
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.view.exclude_director)) {
			// 如果是院长记录，则无权查看
			if (recordDirectorId) {
				const directorRoles = await getUserRoles(recordDirectorId);
				if (hasAnyRole(directorRoles, ['director'])) {
					return {
						hasPermission: false,
						reason: '副院长无权查看院长的病例记录'
					};
				}
			}
			
			return {
				hasPermission: true,
				reason: '具有查看除院长外所有病例记录的权限'
			};
		}
		
		// 检查是否可查看自己主治的病例
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.view.self_doctor)) {
			if (recordDoctorId && recordDoctorId === userId) {
				return {
					hasPermission: true,
					reason: '具有查看自己主治病例记录的权限'
				};
			}
		}
		
		// 检查是否可查看自己协助的病例
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.view.self_assistant)) {
			if (recordAssistantIds && Array.isArray(recordAssistantIds) && recordAssistantIds.includes(userId)) {
				return {
					hasPermission: true,
					reason: '具有查看自己协助病例记录的权限'
				};
			}
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, 'medical_record', 'view', recordDoctorId);
		if (tempAuthResult.hasPermission) {
			return tempAuthResult;
		}
		
		// 默认无权限
		return {
			hasPermission: false,
			reason: '无查看病例记录的权限'
		};
	} catch (error) {
		console.error('[checkMedicalRecordViewPermission] 权限检查失败:', error);
		return {
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 检查病例记录编辑权限
 * @param {String} userId - 用户ID
 * @param {String} recordDoctorId - 病例记录的主治医生ID（可选）
 * @param {String} recordAssistantIds - 病例记录的协助人员ID数组（可选）
 * @returns {Promise<Object>} 权限检查结果 { hasPermission: boolean, reason: string }
 */
async function checkMedicalRecordEditPermission(userId, recordDoctorId = null, recordAssistantIds = null) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 检查是否可编辑所有记录
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.edit.all)) {
			return {
				hasPermission: true,
				reason: '具有编辑所有病例记录的权限'
			};
		}
		
		// 检查是否可编辑自己主治的病例
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.edit.self_doctor)) {
			if (recordDoctorId && recordDoctorId === userId) {
				return {
					hasPermission: true,
					reason: '具有编辑自己主治病例记录的权限'
				};
			}
		}
		
		// 检查是否可编辑自己协助的病例
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.edit.self_assistant)) {
			if (recordAssistantIds && Array.isArray(recordAssistantIds) && recordAssistantIds.includes(userId)) {
				return {
					hasPermission: true,
					reason: '具有编辑自己协助病例记录的权限'
				};
			}
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, 'medical_record', 'edit', recordDoctorId);
		if (tempAuthResult.hasPermission) {
			return tempAuthResult;
		}
		
		// 默认无权限
		return {
			hasPermission: false,
			reason: '无编辑病例记录的权限'
		};
	} catch (error) {
		console.error('[checkMedicalRecordEditPermission] 权限检查失败:', error);
		return {
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 检查病例记录删除权限
 * @param {String} userId - 用户ID
 * @param {String} recordDoctorId - 病例记录的主治医生ID（可选）
 * @param {String} recordAssistantIds - 病例记录的协助人员ID数组（可选）
 * @returns {Promise<Object>} 权限检查结果 { hasPermission: boolean, reason: string }
 */
async function checkMedicalRecordDeletePermission(userId, recordDoctorId = null, recordAssistantIds = null) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 检查是否可删除所有记录
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.delete.all)) {
			return {
				hasPermission: true,
				reason: '具有删除所有病例记录的权限'
			};
		}
		
		// 检查是否可删除自己主治的病例
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.delete.self_doctor)) {
			if (recordDoctorId && recordDoctorId === userId) {
				return {
					hasPermission: true,
					reason: '具有删除自己主治病例记录的权限'
				};
			}
		}
		
		// 检查是否可删除自己协助的病例
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.delete.self_assistant)) {
			if (recordAssistantIds && Array.isArray(recordAssistantIds) && recordAssistantIds.includes(userId)) {
				return {
					hasPermission: true,
					reason: '具有删除自己协助病例记录的权限'
				};
			}
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, 'medical_record', 'delete', recordDoctorId);
		if (tempAuthResult.hasPermission) {
			return tempAuthResult;
		}
		
		// 默认无权限
		return {
			hasPermission: false,
			reason: '无删除病例记录的权限'
		};
	} catch (error) {
		console.error('[checkMedicalRecordDeletePermission] 权限检查失败:', error);
		return {
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 检查临时授权
 * @param {String} userId - 用户ID
 * @param {String} resourceType - 资源类型：'income_record', 'medical_record'
 * @param {String} action - 操作类型：'view', 'edit', 'delete', 'add'
 * @param {String} resourceUserId - 资源关联的用户ID（可选）
 * @returns {Promise<Object>} 权限检查结果 { hasPermission: boolean, reason: string }
 */
/**
 * 检查临时授权（带缓存）
 * @param {String} userId - 用户ID
 * @param {String} resourceType - 资源类型
 * @param {String} action - 操作类型
 * @param {String} resourceUserId - 资源关联的用户ID（可选）
 * @param {Object} resourceData - 资源数据（用于条件授权检查）
 * @returns {Promise<Object>} 检查结果 { hasPermission: boolean, reason: string, authType?: string, authId?: string }
 */
async function checkTemporaryAuth(userId, resourceType, action, resourceUserId = null, resourceData = null) {
	try {
		// 检查缓存
		const cacheKey = `temp:${userId}:${resourceType}:${action}:${resourceUserId || 'all'}`;
		const cached = permissionCache.temporaryAuth.get(cacheKey);
		
		if (cached && (Date.now() - cached.timestamp < permissionCache.cacheTimeout)) {
			return cached.result;
		}
		
		// 查询临时授权表
		const now = Date.now();
		const res = await db.collection('dh-temporary-authorizations')
			.where({
				user_id: userId,
				resource_type: resourceType,
				action: action,
				status: 'active',  // 仅查询激活状态的授权
				start_time: _.lte(now),  // 授权已开始
				end_time: _.gte(now)  // 授权未过期
			})
			.get();
		
		const auths = res.result?.data || res.data || [];
		let result;
		
		if (auths.length === 0) {
			result = {
				hasPermission: false,
				reason: '无临时授权'
			};
		} else {
			// 检查是否有特定资源的授权
			if (resourceUserId) {
				const specificAuth = auths.find(auth => 
					auth.resource_user_id && auth.resource_user_id === resourceUserId
				);
				
				if (specificAuth) {
					result = {
						hasPermission: true,
						reason: '具有特定资源的临时授权',
						authId: specificAuth._id,
						authType: 'specific'
					};
				}
			}
			
			// 如果没有特定资源授权，检查是否有全局授权
			if (!result) {
				const globalAuth = auths.find(auth => !auth.resource_user_id);
				if (globalAuth) {
					result = {
						hasPermission: true,
						reason: '具有全局临时授权',
						authId: globalAuth._id,
						authType: 'global'
					};
				}
			}
			
			// 如果还没有授权，检查是否有条件授权
			if (!result && resourceData) {
				const conditionalAuths = auths.filter(auth => auth.auth_type === 'conditional');
				for (const auth of conditionalAuths) {
					if (auth.conditions && checkConditionsMatch(auth.conditions, resourceData)) {
						result = {
							hasPermission: true,
							reason: '具有条件临时授权',
							authId: auth._id,
							authType: 'conditional'
						};
						break;
					}
				}
				
				if (!result) {
					// 有授权但不符合当前资源
					result = {
						hasPermission: false,
						reason: '临时授权不符合当前资源'
					};
				}
			}
		}
		
		// 更新缓存
		permissionCache.temporaryAuth.set(cacheKey, {
			result,
			timestamp: Date.now()
		});
		
		return result;
	} catch (error) {
		console.error('[checkTemporaryAuth] 临时授权检查失败:', error);
		return {
			hasPermission: false,
			reason: '临时授权检查失败'
		};
	}
}

/**
 * 构建收入记录查询条件
 * 根据用户权限自动构建查询条件，确保用户只能查询有权限的记录
 * @param {String} userId - 用户ID
 * @param {Object} baseConditions - 基础查询条件（可选）
 * @returns {Promise<Object>} 查询条件和权限信息 { conditions: Object, hasPermission: boolean, reason: string }
 */
async function buildIncomeRecordQueryConditions(userId, baseConditions = {}) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 初始化查询条件
		let conditions = { ...baseConditions };
		
		// 检查是否可查看所有记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.view.all)) {
			return {
				conditions,
				hasPermission: true,
				reason: '具有查看所有收入记录的权限'
			};
		}
		
		// 检查是否可查看除院长外的所有记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.view.exclude_director)) {
			// 需要排除院长记录
			// 获取所有院长用户ID
			const directorsRes = await db.collection('uni-id-users')
				.where({ role: 'director' })
				.field({ _id: true })
				.get();
			
			const directorIds = (directorsRes.result?.data || directorsRes.data || []).map(user => user._id);
			
			// 添加排除条件
			if (directorIds.length > 0) {
				conditions.user_id = _.nin(directorIds);
			}
			
			return {
				conditions,
				hasPermission: true,
				reason: '具有查看除院长外所有收入记录的权限'
			};
		}
		
		// 检查是否可查看自己的记录
		if (hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.view.self)) {
			// 只能查看自己的记录
			conditions.user_id = userId;
			
			return {
				conditions,
				hasPermission: true,
				reason: '具有查看自己收入记录的权限'
			};
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, 'income_record', 'view');
		if (tempAuthResult.hasPermission) {
			// 如果是特定资源授权，添加资源用户ID条件
			if (tempAuthResult.authType === 'specific') {
				// 需要查询授权表获取具体的resource_user_id
				const authRes = await db.collection('dh-temporary-authorizations')
					.doc(tempAuthResult.authId)
					.get();
				
				const auth = authRes.result?.data || authRes.data;
				if (auth && auth.resource_user_id) {
					conditions.user_id = auth.resource_user_id;
				}
			}
			
			return {
				conditions,
				hasPermission: true,
				reason: tempAuthResult.reason
			};
		}
		
		// 默认无权限，返回一个永远无法匹配的条件
		conditions._id = 'no_permission';
		
		return {
			conditions,
			hasPermission: false,
			reason: '无查看收入记录的权限'
		};
	} catch (error) {
		console.error('[buildIncomeRecordQueryConditions] 构建查询条件失败:', error);
		
		// 出错时返回一个永远无法匹配的条件
		conditions._id = 'permission_check_error';
		
		return {
			conditions,
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 构建病例记录查询条件
 * 根据用户权限自动构建查询条件，确保用户只能查询有权限的记录
 * @param {String} userId - 用户ID
 * @param {Object} baseConditions - 基础查询条件（可选）
 * @returns {Promise<Object>} 查询条件和权限信息 { conditions: Object, hasPermission: boolean, reason: string }
 */
async function buildMedicalRecordQueryConditions(userId, baseConditions = {}) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 初始化查询条件
		let conditions = { ...baseConditions };
		
		// 检查是否可查看所有记录
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.view.all)) {
			return {
				conditions,
				hasPermission: true,
				reason: '具有查看所有病例记录的权限'
			};
		}
		
		// 检查是否可查看除院长外的所有记录
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.view.exclude_director)) {
			// 需要排除院长记录
			// 获取所有院长用户ID
			const directorsRes = await db.collection('uni-id-users')
				.where({ role: 'director' })
				.field({ _id: true })
				.get();
			
			const directorIds = (directorsRes.result?.data || directorsRes.data || []).map(user => user._id);
			
			// 添加排除条件
			if (directorIds.length > 0) {
				conditions.doctor_id = _.nin(directorIds);
			}
			
			return {
				conditions,
				hasPermission: true,
				reason: '具有查看除院长外所有病例记录的权限'
			};
		}
		
		// 检查是否可查看自己主治的病例
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.view.self_doctor)) {
			// 只能查看自己主治的病例
			conditions.doctor_id = userId;
			
			return {
				conditions,
				hasPermission: true,
				reason: '具有查看自己主治病例记录的权限'
			};
		}
		
		// 检查是否可查看自己协助的病例
		if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.view.self_assistant)) {
			// 只能查看自己协助的病例
			conditions.assistant_ids = _.in([userId]);
			
			return {
				conditions,
				hasPermission: true,
				reason: '具有查看自己协助病例记录的权限'
			};
		}
		
		// 检查临时授权
		const tempAuthResult = await checkTemporaryAuth(userId, 'medical_record', 'view');
		if (tempAuthResult.hasPermission) {
			// 如果是特定资源授权，添加资源用户ID条件
			if (tempAuthResult.authType === 'specific') {
				// 需要查询授权表获取具体的resource_user_id
				const authRes = await db.collection('dh-temporary-authorizations')
					.doc(tempAuthResult.authId)
					.get();
				
				const auth = authRes.result?.data || authRes.data;
				if (auth && auth.resource_user_id) {
					conditions.doctor_id = auth.resource_user_id;
				}
			}
			
			return {
				conditions,
				hasPermission: true,
				reason: tempAuthResult.reason
			};
		}
		
		// 默认无权限，返回一个永远无法匹配的条件
		conditions._id = 'no_permission';
		
		return {
			conditions,
			hasPermission: false,
			reason: '无查看病例记录的权限'
		};
	} catch (error) {
		console.error('[buildMedicalRecordQueryConditions] 构建查询条件失败:', error);
		
		// 出错时返回一个永远无法匹配的条件
		conditions._id = 'permission_check_error';
		
		return {
			conditions,
			hasPermission: false,
			reason: '权限检查失败'
		};
	}
}

/**
 * 批量创建临时授权
 * @param {String} authUserId - 授权人ID
 * @param {Array} authRequests - 授权请求数组，每个请求包含 { targetUserId, resourceType, action, resourceUserId?, duration? }
 * @returns {Promise<Object>} 创建结果 { success: boolean, message: string, results?: Array }
 */
async function batchCreateTemporaryAuth(authUserId, authRequests) {
	try {
		// 验证授权人权限
		const authUserRoles = await getUserRoles(authUserId);
		
		// 只有管理员可以创建临时授权
		if (!hasAnyRole(authUserRoles, ['admin', 'director', 'vice_director'])) {
			return {
				success: false,
				message: '无权限创建临时授权'
			};
		}
		
		if (!Array.isArray(authRequests) || authRequests.length === 0) {
			return {
				success: false,
				message: '无效的授权请求'
			};
		}
		
		const results = [];
		let successCount = 0;
		
		for (const request of authRequests) {
			const { targetUserId, resourceType, action, resourceUserId, duration } = request;
			
			// 验证必填字段
			if (!targetUserId || !resourceType || !action) {
				results.push({
					success: false,
					message: '缺少必填字段',
					request
				});
				continue;
			}
			
			// 创建单个临时授权
			const result = await createTemporaryAuth(
				authUserId, 
				targetUserId, 
				resourceType, 
				action, 
				resourceUserId, 
				duration
			);
			
			results.push(result);
			if (result.success) {
				successCount++;
			}
		}
		
		return {
			success: successCount > 0,
			message: `成功创建 ${successCount}/${authRequests.length} 个临时授权`,
			results
		};
	} catch (error) {
		console.error('[batchCreateTemporaryAuth] 批量创建临时授权失败:', error);
		return {
			success: false,
			message: '批量创建临时授权失败'
		};
	}
}

/**
 * 创建条件临时授权（基于特定条件而非特定资源）
 * @param {String} authUserId - 授权人ID
 * @param {String} targetUserId - 被授权用户ID
 * @param {String} resourceType - 资源类型：'income_record', 'medical_record'
 * @param {String} action - 操作类型：'view', 'edit', 'delete', 'add'
 * @param {Object} conditions - 授权条件，例如 { department: '口腔科', date_range: { start, end } }
 * @param {Number} duration - 授权时长（毫秒），默认24小时
 * @returns {Promise<Object>} 创建结果 { success: boolean, message: string, authId?: string }
 */
async function createConditionalTemporaryAuth(authUserId, targetUserId, resourceType, action, conditions = {}, duration = 24 * 60 * 60 * 1000) {
	try {
		// 验证授权人权限
		const authUserRoles = await getUserRoles(authUserId);
		
		// 只有管理员可以创建临时授权
		if (!hasAnyRole(authUserRoles, ['admin', 'director', 'vice_director'])) {
			return {
				success: false,
				message: '无权限创建临时授权'
			};
		}
		
		// 验证资源类型和操作类型
		if (!['income_record', 'medical_record'].includes(resourceType)) {
			return {
				success: false,
				message: '无效的资源类型'
			};
		}
		
		if (!['view', 'edit', 'delete', 'add'].includes(action)) {
			return {
				success: false,
				message: '无效的操作类型'
			};
		}
		
		// 创建条件临时授权
		const now = Date.now();
		const startTime = now;
		const endTime = now + duration;
		
		const authData = {
			user_id: targetUserId,
			resource_type: resourceType,
			action: action,
			conditions: conditions,
			status: 'active',
			start_time: startTime,
			end_time: endTime,
			created_by: authUserId,
			create_time: now,
			auth_type: 'conditional' // 标记为条件授权
		};
		
		const createRes = await db.collection('dh-temporary-authorizations').add(authData);
		const authId = createRes.id;
		
		// 记录权限日志
		await logPermissionAction(authUserId, 'create_conditional_temp_auth', {
			targetUserId,
			resourceType,
			action,
			conditions,
			authId
		});
		
		return {
			success: true,
			message: '条件临时授权创建成功',
			authId
		};
	} catch (error) {
		console.error('[createConditionalTemporaryAuth] 创建条件临时授权失败:', error);
		return {
			success: false,
			message: '创建条件临时授权失败'
		};
	}
}

/**
 * 权限检查单元测试函数
 * @param {String} testType - 测试类型：'unit'（单元测试）、'integration'（集成测试）
 * @param {Object} testData - 测试数据，包含用户ID、角色等信息
 * @returns {Promise<Object>} 测试结果 { success: boolean, results: Array, summary: Object }
 */
async function runPermissionTests(testType = 'unit', testData = {}) {
	const testResults = [];
	let passedTests = 0;
	let totalTests = 0;
	
	try {
		// 测试数据准备
		const testUserId = testData.userId || 'test_user_id';
		const testRoles = testData.roles || ['doctor'];
		const testResourceUserId = testData.resourceUserId || 'resource_user_id';
		
		// 模拟用户角色
		const originalGetUserRoles = module.exports.getUserRoles;
		module.exports.getUserRoles = async () => testRoles;
		
		// 1. 测试基础函数
		totalTests++;
		try {
			const roles = await getUserRoles(testUserId);
			const hasRole = hasAnyRole(roles, ['doctor']);
			
			testResults.push({
				test: '基础函数测试',
				status: 'passed',
				message: 'getUserRoles和hasAnyRole函数正常工作',
				details: { roles, hasRole }
			});
			passedTests++;
		} catch (error) {
			testResults.push({
				test: '基础函数测试',
				status: 'failed',
				message: error.message,
				details: { error: error.toString() }
			});
		}
		
		// 2. 测试通用权限检查函数
		totalTests++;
		try {
			const result = await checkPermission(testUserId, 'income_record', 'view', testResourceUserId);
			const expectedStatus = testRoles.includes('admin') || testRoles.includes('director') ? true : false;
			
			if (result.hasPermission === expectedStatus) {
				testResults.push({
					test: '通用权限检查函数测试',
					status: 'passed',
					message: 'checkPermission函数正常工作',
					details: { result, expectedStatus }
				});
				passedTests++;
			} else {
				testResults.push({
					test: '通用权限检查函数测试',
					status: 'failed',
					message: `预期权限状态为${expectedStatus}，实际为${result.hasPermission}`,
					details: { result, expectedStatus }
				});
			}
		} catch (error) {
			testResults.push({
				test: '通用权限检查函数测试',
				status: 'failed',
				message: error.message,
				details: { error: error.toString() }
			});
		}
		
		// 3. 测试收入记录权限检查
		totalTests++;
		try {
			const viewResult = await checkIncomeRecordViewPermission(testUserId, testResourceUserId);
			const editResult = await checkIncomeRecordEditPermission(testUserId, testResourceUserId);
			const deleteResult = await checkIncomeRecordDeletePermission(testUserId, testResourceUserId);
			const addResult = await checkIncomeRecordAddPermission(testUserId);
			
			testResults.push({
				test: '收入记录权限检查测试',
				status: 'passed',
				message: '收入记录权限检查函数正常工作',
				details: { viewResult, editResult, deleteResult, addResult }
			});
			passedTests++;
		} catch (error) {
			testResults.push({
				test: '收入记录权限检查测试',
				status: 'failed',
				message: error.message,
				details: { error: error.toString() }
			});
		}
		
		// 4. 测试病例记录权限检查
		totalTests++;
		try {
			const viewResult = await checkMedicalRecordViewPermission(testUserId, testResourceUserId);
			const editResult = await checkMedicalRecordEditPermission(testUserId, testResourceUserId);
			const deleteResult = await checkMedicalRecordDeletePermission(testUserId, testResourceUserId);
			
			testResults.push({
				test: '病例记录权限检查测试',
				status: 'passed',
				message: '病例记录权限检查函数正常工作',
				details: { viewResult, editResult, deleteResult }
			});
			passedTests++;
		} catch (error) {
			testResults.push({
				test: '病例记录权限检查测试',
				status: 'failed',
				message: error.message,
				details: { error: error.toString() }
			});
		}
		
		// 5. 测试查询条件构建
		totalTests++;
		try {
			const incomeQueryResult = await buildIncomeRecordQueryConditions(testUserId);
			const medicalQueryResult = await buildMedicalRecordQueryConditions(testUserId);
			
			testResults.push({
				test: '查询条件构建测试',
				status: 'passed',
				message: '查询条件构建函数正常工作',
				details: { incomeQueryResult, medicalQueryResult }
			});
			passedTests++;
		} catch (error) {
			testResults.push({
				test: '查询条件构建测试',
				status: 'failed',
				message: error.message,
				details: { error: error.toString() }
			});
		}
		
		// 6. 测试批量权限检查
		totalTests++;
		try {
			const batchRequests = [
				{ resourceType: 'income_record', action: 'view', resourceUserId: testResourceUserId },
				{ resourceType: 'medical_record', action: 'edit', resourceUserId: testResourceUserId }
			];
			
			const batchResult = await batchCheckPermissions(testUserId, batchRequests);
			
			testResults.push({
				test: '批量权限检查测试',
				status: 'passed',
				message: '批量权限检查函数正常工作',
				details: { batchResult }
			});
			passedTests++;
		} catch (error) {
			testResults.push({
				test: '批量权限检查测试',
				status: 'failed',
				message: error.message,
				details: { error: error.toString() }
			});
		}
		
		// 7. 测试条件匹配
		totalTests++;
		try {
			const conditions = {
				department: '口腔科',
				date_range: {
					start: '2023-01-01',
					end: '2023-12-31'
				}
			};
			
			const resourceData = {
				department: '口腔科',
				create_time: '2023-06-15'
			};
			
			const matchResult = checkConditionsMatch(conditions, resourceData);
			
			testResults.push({
				test: '条件匹配测试',
				status: 'passed',
				message: '条件匹配函数正常工作',
				details: { conditions, resourceData, matchResult }
			});
			passedTests++;
		} catch (error) {
			testResults.push({
				test: '条件匹配测试',
				status: 'failed',
				message: error.message,
				details: { error: error.toString() }
			});
		}
		
		// 恢复原始函数
		module.exports.getUserRoles = originalGetUserRoles;
		
		// 记录测试日志
		await logPermissionAction(testUserId, 'permission_test', {
			testType,
			testResults,
			passedTests,
			totalTests
		});
		
		return {
			success: passedTests === totalTests,
			results: testResults,
			summary: {
				totalTests,
				passedTests,
				failedTests: totalTests - passedTests,
				successRate: totalTests > 0 ? (passedTests / totalTests * 100).toFixed(2) + '%' : '0%'
			}
		};
	} catch (error) {
		console.error('[runPermissionTests] 权限测试执行失败:', error);
		return {
			success: false,
			results: testResults,
			summary: {
				totalTests,
				passedTests,
				failedTests: totalTests - passedTests,
				error: error.message
			}
		};
	}
}

/**
 * 权限性能测试函数
 * @param {Number} iterations - 测试迭代次数
 * @param {String} testFunction - 要测试的函数名
 * @returns {Promise<Object>} 性能测试结果
 */
async function runPermissionPerformanceTest(iterations = 100, testFunction = 'checkPermission') {
	const testUserId = 'performance_test_user';
	const testResourceUserId = 'performance_test_resource';
	const testResourceType = 'income_record';
	const testAction = 'view';
	
	try {
		// 预热
		for (let i = 0; i < 10; i++) {
			await module.exports[testFunction](testUserId, testResourceType, testAction, testResourceUserId);
		}
		
		// 性能测试
		const startTime = Date.now();
		
		for (let i = 0; i < iterations; i++) {
			await module.exports[testFunction](testUserId, testResourceType, testAction, testResourceUserId);
		}
		
		const endTime = Date.now();
		const totalTime = endTime - startTime;
		const avgTime = totalTime / iterations;
		
		// 记录性能测试日志
		await logPermissionAction(testUserId, 'permission_performance_test', {
			testFunction,
			iterations,
			totalTime,
			avgTime
		});
		
		return {
			success: true,
			testFunction,
			iterations,
			totalTime,
			avgTime,
			throughput: (iterations / totalTime * 1000).toFixed(2) + ' ops/sec'
		};
	} catch (error) {
		console.error('[runPermissionPerformanceTest] 性能测试执行失败:', error);
		return {
			success: false,
			testFunction,
			iterations,
			error: error.message
		};
	}
}

/**
 * 检查资源数据是否满足条件
 * @param {Object} conditions - 条件对象
 * @param {Object} resourceData - 资源数据
 * @returns {Boolean} 是否满足条件
 */
function checkConditionsMatch(conditions, resourceData) {
	if (!conditions || !resourceData) {
		return false;
	}
	
	// 检查部门条件
	if (conditions.department && resourceData.department !== conditions.department) {
		return false;
	}
	
	// 检查日期范围条件
	if (conditions.date_range) {
		const { start, end } = conditions.date_range;
		const resourceDate = new Date(resourceData.create_time || resourceData.date);
		
		if (start && resourceDate < new Date(start)) {
			return false;
		}
		
		if (end && resourceDate > new Date(end)) {
			return false;
		}
	}
	
	// 检查其他条件
	if (conditions.custom_conditions && Array.isArray(conditions.custom_conditions)) {
		for (const condition of conditions.custom_conditions) {
			const { field, operator, value } = condition;
			const fieldValue = resourceData[field];
			
			if (operator === 'equals' && fieldValue !== value) {
				return false;
			}
			
			if (operator === 'not_equals' && fieldValue === value) {
				return false;
			}
			
			if (operator === 'in' && Array.isArray(value) && !value.includes(fieldValue)) {
				return false;
			}
			
			if (operator === 'not_in' && Array.isArray(value) && value.includes(fieldValue)) {
				return false;
			}
			
			if (operator === 'greater_than' && fieldValue <= value) {
				return false;
			}
			
			if (operator === 'less_than' && fieldValue >= value) {
				return false;
			}
		}
	}
	
	return true;
}

/**
 * 创建临时授权
 * @param {String} authUserId - 授权人ID
 * @param {String} targetUserId - 被授权用户ID
 * @param {String} resourceType - 资源类型：'income_record', 'medical_record'
 * @param {String} action - 操作类型：'view', 'edit', 'delete', 'add'
 * @param {String} resourceUserId - 资源关联的用户ID（可选，用于特定资源授权）
 * @param {Number} duration - 授权时长（毫秒），默认24小时
 * @returns {Promise<Object>} 创建结果 { success: boolean, message: string, authId?: string }
 */
async function createTemporaryAuth(authUserId, targetUserId, resourceType, action, resourceUserId = null, duration = 24 * 60 * 60 * 1000) {
	try {
		// 验证授权人权限
		const authUserRoles = await getUserRoles(authUserId);
		
		// 只有管理员可以创建临时授权
		if (!hasAnyRole(authUserRoles, ['admin', 'director', 'vice_director'])) {
			return {
				success: false,
				message: '无权限创建临时授权'
			};
		}
		
		// 验证资源类型和操作类型
		if (!['income_record', 'medical_record'].includes(resourceType)) {
			return {
				success: false,
				message: '无效的资源类型'
			};
		}
		
		if (!['view', 'edit', 'delete', 'add'].includes(action)) {
			return {
				success: false,
				message: '无效的操作类型'
			};
		}
		
		// 检查是否已存在相同的临时授权
		const now = Date.now();
		const existingAuthRes = await db.collection('dh-temporary-authorizations')
			.where({
				user_id: targetUserId,
				resource_type: resourceType,
				action: action,
				resource_user_id: resourceUserId || _.exists(false),
				status: 'active',
				end_time: _.gte(now)
			})
			.get();
		
		const existingAuths = existingAuthRes.result?.data || existingAuthRes.data || [];
		
		if (existingAuths.length > 0) {
			return {
				success: false,
				message: '已存在相同的临时授权'
			};
		}
		
		// 创建临时授权
		const startTime = now;
		const endTime = now + duration;
		
		const authData = {
			user_id: targetUserId,
			resource_type: resourceType,
			action: action,
			resource_user_id: resourceUserId,
			status: 'active',
			start_time: startTime,
			end_time: endTime,
			created_by: authUserId,
			create_time: now
		};
		
		const createRes = await db.collection('dh-temporary-authorizations').add(authData);
		const authId = createRes.id;
		
		// 记录权限日志
		await logPermissionAction(authUserId, 'create_temp_auth', {
			targetUserId,
			resourceType,
			action,
			resourceUserId,
			authId
		});
		
		return {
			success: true,
			message: '临时授权创建成功',
			authId
		};
	} catch (error) {
		console.error('[createTemporaryAuth] 创建临时授权失败:', error);
		return {
			success: false,
			message: '创建临时授权失败'
		};
	}
}

/**
 * 撤销临时授权
 * @param {String} authUserId - 操作人ID
 * @param {String} authId - 授权ID
 * @returns {Promise<Object>} 撤销结果 { success: boolean, message: string }
 */
async function revokeTemporaryAuth(authUserId, authId) {
	try {
		// 验证操作人权限
		const authUserRoles = await getUserRoles(authUserId);
		
		// 只有管理员可以撤销临时授权
		if (!hasAnyRole(authUserRoles, ['admin', 'director', 'vice_director'])) {
			return {
				success: false,
				message: '无权限撤销临时授权'
			};
		}
		
		// 获取授权信息
		const authRes = await db.collection('dh-temporary-authorizations').doc(authId).get();
		const auth = authRes.result?.data || authRes.data;
		
		if (!auth) {
			return {
				success: false,
				message: '授权不存在'
			};
		}
		
		// 撤销授权
		await db.collection('dh-temporary-authorizations').doc(authId).update({
			status: 'revoked',
			revoke_time: Date.now(),
			revoked_by: authUserId
		});
		
		// 记录权限日志
		await logPermissionAction(authUserId, 'revoke_temp_auth', {
			authId,
			targetUserId: auth.user_id,
			resourceType: auth.resource_type,
			action: auth.action
		});
		
		return {
			success: true,
			message: '临时授权撤销成功'
		};
	} catch (error) {
		console.error('[revokeTemporaryAuth] 撤销临时授权失败:', error);
		return {
			success: false,
			message: '撤销临时授权失败'
		};
	}
}

/**
 * 获取用户的临时授权列表
 * @param {String} userId - 用户ID
 * @param {String} resourceType - 资源类型（可选）
 * @returns {Promise<Array>} 临时授权列表
 */
async function getUserTemporaryAuths(userId, resourceType = null) {
	try {
		const now = Date.now();
		let query = {
			user_id: userId,
			status: 'active',
			start_time: _.lte(now),
			end_time: _.gte(now)
		};
		
		if (resourceType) {
			query.resource_type = resourceType;
		}
		
		const authsRes = await db.collection('dh-temporary-authorizations')
			.where(query)
			.orderBy('end_time', 'asc')
			.get();
		
		return authsRes.result?.data || authsRes.data || [];
	} catch (error) {
		console.error('[getUserTemporaryAuths] 获取临时授权列表失败:', error);
		return [];
	}
}

/**
 * 权限错误处理类
 */
class PermissionError extends Error {
	constructor(message, code = 'PERMISSION_ERROR', details = {}) {
		super(message);
		this.name = 'PermissionError';
		this.code = code;
		this.details = details;
	}
}

/**
 * 统一错误处理函数
 * @param {Error} error - 错误对象
 * @param {String} context - 错误上下文
 * @param {Object} additionalInfo - 额外信息
 * @returns {Object} 标准化错误响应
 */
function handlePermissionError(error, context, additionalInfo = {}) {
	const errorInfo = {
		success: false,
		message: '权限检查失败',
		context,
		timestamp: new Date().toISOString(),
		...additionalInfo
	};
	
	if (error instanceof PermissionError) {
		errorInfo.message = error.message;
		errorInfo.code = error.code;
		errorInfo.details = error.details;
	} else {
		errorInfo.code = 'UNKNOWN_ERROR';
		errorInfo.details = {
			originalError: error.message,
			stack: error.stack
		};
	}
	
	// 记录错误日志
	console.error(`[PermissionError] ${context}:`, errorInfo);
	
	// 异步记录到数据库（不阻塞响应）
	logPermissionAction(additionalInfo.userId || 'system', 'permission_error', errorInfo)
		.catch(logError => console.error('记录权限错误日志失败:', logError));
	
	return errorInfo;
}

/**
 * 增强的权限日志记录函数
 * @param {String} userId - 操作人ID
 * @param {String} action - 操作类型
 * @param {Object} details - 操作详情
 * @param {String} level - 日志级别：'info', 'warn', 'error'
 * @returns {Promise<Boolean>} 是否记录成功
 */
async function logPermissionAction(userId, action, details = {}, level = 'info') {
	try {
		const logEntry = {
			user_id: userId,
			action,
			details,
			level,
			timestamp: Date.now(),
			ip: details.ip || '',
			user_agent: details.user_agent || '',
			resource_type: details.resourceType || '',
			resource_id: details.resourceId || ''
		};
		
		// 记录到数据库
		await db.collection('dh-permission-logs').add(logEntry);
		
		// 根据日志级别决定是否输出到控制台
		switch (level) {
			case 'error':
				console.error(`[PermissionLog] ${action}:`, logEntry);
				break;
			case 'warn':
				console.warn(`[PermissionLog] ${action}:`, logEntry);
				break;
			default:
				console.log(`[PermissionLog] ${action}:`, logEntry);
		}
		
		return true;
	} catch (error) {
		console.error('[logPermissionAction] 记录权限日志失败:', error);
		return false;
	}
}

/**
 * 获取权限日志（支持分页和筛选）
 * @param {String} userId - 用户ID（可选）
 * @param {String} action - 操作类型（可选）
 * @param {String} level - 日志级别（可选）
 * @param {Number} page - 页码，从1开始
 * @param {Number} pageSize - 每页大小
 * @param {Object} dateRange - 日期范围 { start, end }
 * @returns {Promise<Object>} 查询结果 { logs: Array, total: Number, page: Number, pageSize: Number }
 */
async function getPermissionLogs(userId = null, action = null, level = null, page = 1, pageSize = 20, dateRange = null) {
	try {
		// 构建查询条件
		let query = {};
		
		if (userId) {
			query.user_id = userId;
		}
		
		if (action) {
			query.action = action;
		}
		
		if (level) {
			query.level = level;
		}
		
		if (dateRange) {
			if (dateRange.start) {
				query.timestamp = query.timestamp || {};
				query.timestamp.$gte = new Date(dateRange.start).getTime();
			}
			
			if (dateRange.end) {
				query.timestamp = query.timestamp || {};
				query.timestamp.$lte = new Date(dateRange.end).getTime();
			}
		}
		
		// 获取总数
		const countRes = await db.collection('dh-permission-logs')
			.where(query)
			.count();
		
		const total = countRes.result?.total || countRes.total || 0;
		
		// 分页查询
		const skip = (page - 1) * pageSize;
		const logsRes = await db.collection('dh-permission-logs')
			.where(query)
			.orderBy('timestamp', 'desc')
			.skip(skip)
			.limit(pageSize)
			.get();
		
		const logs = logsRes.result?.data || logsRes.data || [];
		
		return {
			logs,
			total,
			page,
			pageSize,
			totalPages: Math.ceil(total / pageSize)
		};
	} catch (error) {
		console.error('[getPermissionLogs] 获取权限日志失败:', error);
		return {
			logs: [],
			total: 0,
			page,
			pageSize,
			totalPages: 0,
			error: '获取权限日志失败'
		};
	}
}





/**
 * 检查用户是否有管理权限
 * @param {String} userId - 用户ID
 * @returns {Promise<Boolean>} 是否有管理权限
 */
async function hasAdminPermission(userId) {
	try {
		const userRoles = await getUserRoles(userId);
		return hasAnyRole(userRoles, ['admin', 'director', 'vice_director']);
	} catch (error) {
		console.error('[hasAdminPermission] 检查管理权限失败:', error);
		return false;
	}
}

/**
 * 获取用户可访问的资源列表
 * @param {String} userId - 用户ID
 * @param {String} resourceType - 资源类型：'income_record', 'medical_record'
 * @param {String} action - 操作类型：'view', 'edit', 'delete', 'add'
 * @returns {Promise<Array>} 可访问的资源ID列表
 */
async function getUserAccessibleResources(userId, resourceType, action) {
	try {
		// 获取用户角色
		const userRoles = await getUserRoles(userId);
		
		// 检查是否有全局权限
		let hasGlobalPermission = false;
		
		if (resourceType === 'income_record') {
			if (action === 'view' && hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.view.all)) {
				hasGlobalPermission = true;
			} else if (action === 'edit' && hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.edit.all)) {
				hasGlobalPermission = true;
			} else if (action === 'delete' && hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.delete.all)) {
				hasGlobalPermission = true;
			} else if (action === 'add' && hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.add.all)) {
				hasGlobalPermission = true;
			}
		} else if (resourceType === 'medical_record') {
			if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS[action]?.all || [])) {
				hasGlobalPermission = true;
			}
		}
		
		// 如果有全局权限，返回null表示可访问所有资源
		if (hasGlobalPermission) {
			return null;
		}
		
		// 获取临时授权
		const tempAuths = await getUserTemporaryAuths(userId, resourceType);
		const globalAuth = tempAuths.find(auth => !auth.resource_user_id && auth.action === action);
		
		// 如果有全局临时授权，返回null表示可访问所有资源
		if (globalAuth) {
			return null;
		}
		
		// 收集特定资源授权
		const specificAuths = tempAuths.filter(auth => auth.resource_user_id && auth.action === action);
		const resourceIds = specificAuths.map(auth => auth.resource_user_id);
		
		// 根据角色添加自有资源
		if (resourceType === 'income_record') {
			if (action === 'view' && hasAnyRole(userRoles, INCOME_RECORD_PERMISSIONS.view.self)) {
				resourceIds.push(userId);
			}
		} else if (resourceType === 'medical_record') {
			if (hasAnyRole(userRoles, MEDICAL_RECORD_PERMISSIONS.view.self_doctor || [])) {
				resourceIds.push(userId);
			}
		}
		
		// 去重并返回
		return [...new Set(resourceIds)];
	} catch (error) {
		console.error('[getUserAccessibleResources] 获取可访问资源失败:', error);
		return [];
	}
}

module.exports = {
	// 权限常量
	INCOME_RECORD_PERMISSIONS,
	MEDICAL_RECORD_PERMISSIONS,
	
	// 基础函数
	getUserRoles,
	hasAnyRole,
	checkTemporaryAuth,
	hasAdminPermission,
	
	// 通用权限函数
	checkPermission,
	getPermissionConfig,
	batchCheckPermissions,
	clearExpiredCache,
	
	// 收入记录权限检查
	checkIncomeRecordViewPermission,
	checkIncomeRecordEditPermission,
	checkIncomeRecordDeletePermission,
	checkIncomeRecordAddPermission,
	buildIncomeRecordQueryConditions,
	
	// 病例记录权限检查
	checkMedicalRecordViewPermission,
	checkMedicalRecordEditPermission,
	checkMedicalRecordDeletePermission,
	buildMedicalRecordQueryConditions,
	
	// 临时授权管理
	createTemporaryAuth,
	revokeTemporaryAuth,
	getUserTemporaryAuths,
	batchCreateTemporaryAuth,
	createConditionalTemporaryAuth,
	
	// 权限日志
	logPermissionAction,
	getPermissionLogs,
	
	// 错误处理
	PermissionError,
	handlePermissionError,
	
	// 资源访问
	getUserAccessibleResources,
	
	// 条件匹配
	checkConditionsMatch,
	
	// 权限测试
	runPermissionTests,
	runPermissionPerformanceTest
};